import django_filters
from main.filters import NumberInFilter
from main.models import Task
from main.permissions import DjangoModelFullPermissions
from rest_framework import permissions, request, serializers, viewsets


class TaskSerializer(serializers.ModelSerializer):
    creator = serializers.PrimaryKeyRelatedField(read_only=True, required=False)
    executor = serializers.PrimaryKeyRelatedField(
        read_only=True, required=False
    )
    request = serializers.PrimaryKeyRelatedField(read_only=True, required=False)
    order = serializers.PrimaryKeyRelatedField(read_only=True, required=False)

    class Meta:
        model = Task
        fields = (
            "id",
            "title",
            "description",
            "status",
            "deadline",
            "created_on",
            "updated_on",
            "creator",
            "executor",
            "request",
            "order",
        )


class TaskFilter(django_filters.FilterSet):
    ids = NumberInFilter(field_name="id", lookup_expr="in")

    class Meta:
        model = Task
        fields = ("id", "request", "order", "executor", "status")


class TaskPermissions(permissions.BasePermission):
    def has_object_permission(
        self, http_request: request.Request, view, obj: Task
    ):
        return (
            obj.executor
            and (
                http_request.user.is_superuser
                or obj.executor == http_request.user.id
            )
        ) or not obj.executor


class TaskViewSet(viewsets.ModelViewSet):
    queryset = Task.objects.all().order_by("status")
    serializer_class = TaskSerializer
    permission_classes = (
        DjangoModelFullPermissions,
        TaskPermissions,
    )
    filterset_class = TaskFilter
